<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
require('includes/application_top.php');
global $db;
//init value
$languages_english_id = "6";
$products_id = $_GET['ddl_products_id'];
$products_serving_size = "0";
$products_serving_size_unit = "g";
$label_measurements_id = "0";
$label_measurements_type = "";
$products_dosis = "0";
$products_serving_type = "serving";

//update info
if(isset($_POST['UPDATE_SERVING']))
{
    $products_serving_size = $_POST['products_serving_size'];
    $products_serving_size_unit = $_POST['products_serving_size_unit'];
    $products_dosis = $_POST['products_dosis'];
    $label_measurements_type = $_POST['products_serving_measurement'];
    $serving = $_POST['serving'];
    $products_serving_measurements = "";
    if(!isset($products_serving_size_unit) || $products_serving_size_unit === "")
        $products_serving_measurements = "";
    else
        $products_serving_measurements = " (" . $products_serving_size . " " . $products_serving_size_unit . ")";
    //update measurement
    $db->Execute("UPDATE products_description pd, label_measurements l
                  SET pd.label_measurements_id=l.label_measurements_id,
                        pd.products_serving_measurement=CONCAT(l.label_measurements_name, '$products_serving_measurements')
                  WHERE pd.products_id=$products_id
                        AND pd.language_id=l.languages_id
                        AND l.label_measurements_type='$label_measurements_type'");    
        
    if($serving === "1")
    {
        //update serving size
        $db->Execute("UPDATE products 
                  SET products_serving_size='$products_serving_size',
                      products_serving_size_unit='$products_serving_size_unit',
                      products_dosis='$products_dosis',
                      products_serving_type='serving'
                  WHERE products_id='$products_id'");
        
        //recalculate products label
        $db->Execute("UPDATE products_label pl, ingredients i
                    SET pl.products_label_qty_100=pl.products_label_qty_serving*100/$products_serving_size,
                        pl.products_label_ddd_serving=pl.products_label_qty_serving/i.ingredients_ddd,
                        pl.products_label_ddr_100=(pl.products_label_qty_serving*100/$products_serving_size)/i.ingredients_ddd
                    WHERE pl.products_id=$products_id
                        AND pl.ingredients_id=i.ingredients_id");   
    }
    else
    {
        //update serving size
        $db->Execute("UPDATE products 
                  SET products_serving_size='$products_serving_size',
                      products_serving_size_unit='$products_serving_size_unit',
                      products_dosis='$products_dosis',
                      products_serving_type='100g'
                  WHERE products_id='$products_id'");
        
        //recalculate products label
        $db->Execute("UPDATE products_label pl, ingredients i
                    SET pl.products_label_qty_serving=pl.products_label_qty_100*$products_serving_size/100,
                        pl.products_label_ddd_serving=(pl.products_label_qty_100*$products_serving_size/100)/i.ingredients_ddd,
                        pl.products_label_ddr_100=pl.products_label_qty_100*100/i.ingredients_ddd
                    WHERE pl.products_id=$products_id
                        AND pl.ingredients_id=i.ingredients_id");   
    }
}
//initial value
$products_serving_measurements = "";
//get product info
if(isset($products_id))
{
    $products_query = $db->Execute("Select p.products_id, p.products_dosis, pd.label_measurements_id, 
                                    p.products_serving_size, p.products_serving_size_unit, products_serving_type,
                                    l.label_measurements_type, pd.products_serving_measurement 
                            from products p join products_description pd on p.products_id = pd.products_id and pd.language_id = '$languages_english_id'
                                join label_measurements l on pd.label_measurements_id = l.label_measurements_id
                            where p.products_id='$products_id'");
    if(!$products_query->EOF)
    {
        $products_dosis = $products_query->fields['products_dosis'];
        $label_measurements_id = $products_query->fields['label_measurements_id'];
        $products_serving_size = $products_query->fields['products_serving_size'];
        $products_serving_type = $products_query->fields['products_serving_type'];
        $products_serving_size_unit = $products_query->fields['products_serving_size_unit'];
        $label_measurements_type = $products_query->fields['label_measurements_type'];
        $products_serving_measurements = $products_query->fields['products_serving_measurement'];
    }
}
//generate products listing
$products_listing = $db->Execute("SELECT products_id, products_name 
                            FROM products_description
                            WHERE language_id='" . $_SESSION['languages_id'] . "'
                            ORDER BY products_name");

if(isset($products_id))
{
    $listing_products_label = $db->Execute("SELECT pl.*, i.ingredients_ddd, i.ingredients_unit, id.ingredients_description 
                            FROM products_label pl join ingredients i on pl.ingredients_id=i.ingredients_id
                                join ingredients_description id on pl.ingredients_id=id.ingredients_id and languages_id='$languages_english_id'
                            WHERE products_id='" . $products_id . "'
                            ORDER BY products_label_sort");
}

//generate measurements listing
$measurements_listing = $db->Execute("SELECT label_measurements_id, label_measurements_type, label_measurements_name 
                            FROM label_measurements
                            WHERE languages_id='$languages_english_id'
                            ORDER BY label_measurements_id");

?>

<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<link rel="stylesheet" type="text/css" href="includes/cssjsmenuhover.css" media="all" id="hoverJS">
<link rel="stylesheet" type="text/css" href="/jquery-ui.css">
<script language="javascript" src="includes/menu.js"></script>
<script language="javascript" src="includes/general.js"></script>
<script type="text/javascript" src="/jquery-1.7.1.js"></script>
<script type="text/javascript" src="/jquery-ui.js"></script>
<script type="text/javascript">
  <!--
  function init()
  {
    cssjsmenu('navbar');
    if (document.getElementById)
    {
      var kill = document.getElementById('hoverJS');
      kill.disabled = true;
    }
  }
  // -->
</script>
</head>
<body onload="init()">    
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->

<!-- dropdown products //-->
<?php 
if($products_listing->RecordCount() > 0)
{
?>
    <form id="frm_products_label" action="products_label_insertion.php" method="GET">
        <select style="margin-left:150px; margin-right:auto; margin-top: 20px;" id="ddl_products_id" name="ddl_products_id" onchange="$('#frm_products_label').submit();">
    <?php
        while(!$products_listing->EOF)
        {
            if($products_listing->fields['products_id'] == $products_id)
                echo "<option selected='selected' value='" . $products_listing->fields['products_id'] . "'>" . $products_listing->fields['products_name'] . "</option>";
            else
                echo "<option value='" . $products_listing->fields['products_id'] . "'>" . $products_listing->fields['products_name'] . "</option>";
            $products_listing->MoveNext();
        }
    ?>
        </select>
    </form>
<?php
}
?>
<!-- dropdown products eof //-->
<form id="form_update_serving" action="products_label_insertion.php?ddl_products_id=<?php echo $products_id;?>" method="post">
    <table style="margin-left:auto; margin-right:auto; margin-top: 20px; margin-bottom:30px; width: 40%">
        <tr>
            <td><b>Product Serving Measurement:</b></td>
            <td>
                <select id="products_serving_measurement" name="products_serving_measurement" onchange="selectLabelMeasurement(this)">                
            <?php
                while(!$measurements_listing->EOF)
                {
                    if($label_measurements_id == $measurements_listing->fields['label_measurements_id'])
                        echo "<option selected='selected' value='" . $measurements_listing->fields['label_measurements_type'] . "'>" . $measurements_listing->fields['label_measurements_name'] . "</option>";
                    else
                        echo "<option value='" . $measurements_listing->fields['label_measurements_type'] . "'>" . $measurements_listing->fields['label_measurements_name'] . "</option>";
                    $measurements_listing->MoveNext();
                }
            ?>
                </select>
            </td>    
        </tr>
        <tr>
            <td><b>Product Serving Size:</b></td>
            <td>
                <input type="text" name="products_serving_size" id="products_serving_size" 
                       value="<?php echo $products_serving_size; ?>" 
                           <?php echo strpos($label_measurements_type,"s") === false ? "readonly='readonly'" : ""; ?> />
            </td>        
        </tr>
        <tr>
            <td><b>Serving Size Unit:</b></td>
            <td>
                <!-- urbano unit -->
                <select name="products_serving_size_unit" id="products_serving_size_unit"
                        <?php echo strpos($label_measurements_type,"s") === false ? "disabled='disabled'" : ""; ?> >
                    <option value=""></option>
                    <option value="g" <?php echo $products_serving_size_unit == "g" ? "selected='selected'" : ""; ?>>g</option>
                    <option value="mg" <?php echo $products_serving_size_unit == "mg" ? "selected='selected'" : ""; ?>>mg</option>
                    <option value="ml" <?php echo $products_serving_size_unit == "ml" ? "selected='selected'" : ""; ?>>ml</option>
                </select>
            </td>        
        </tr>
        <tr>
            <td><b>Product Dosis:</b></td>
            <td>
                <input type="text" name="products_dosis" id="products_dosis" value="<?php echo $products_dosis; ?>" />
            </td>           
        </tr>
        <tr>
            <td colspan="2" align="right">
                <input type="radio" id="rdServing" <?php echo $products_serving_type === "serving" ? 'checked="checked"' : '';?> name="serving" value="1" /><label for="rdServing">Serving</label>
                <input type="radio" id="rd100" <?php echo $products_serving_type === "100g" ? 'checked="checked"' : '';?> name="serving" value="2" /><label for="rd100">100g</label>
                <input type="button" value="Update Serving" onclick="confirmBefore()" />
                <input type="hidden" name="UPDATE_SERVING" value="Y" />
            </td>  
        </tr>
    </table>
</form>
<table style="margin-left:auto; margin-right:auto; margin-top: 20px; margin-bottom:30px; width: 80%">
    <tr>
        <td style="width: 60%" valign="top">
            <table id="tblLabels" style="margin-left:auto; margin-right:auto; margin-top: 20px; margin-bottom:30px; width: 100%">
                <tr class="dataTableHeadingRow">
                    <td>&nbsp;</td><td>&nbsp;</td>
                    <td align="center" class="dataTableHeadingContent">Ingredient</td>
                    <td align="center" class="dataTableHeadingContent">Value</td>
                    <td align="center" class="dataTableHeadingContent">Unit</td>
                    <td align="center" class="dataTableHeadingContent">Type</td>
                    <td>&nbsp;</td><td>&nbsp;</td>
                </tr>
<?php 
if(isset($products_id) && $listing_products_label->RecordCount() > 0)
{
    $ix = 0;    
    while(!$listing_products_label->EOF)
    {
?>
                <tr class="dataTableRow row_<?php echo $listing_products_label->fields['products_label_id']; ?>">
                    <td align="center" style="width: 32px">
    <?php if($ix > 0) {?>
                        <a href="javascript:void(0)" onclick="UP('<?php echo $listing_products_label->fields['products_label_id']; ?>')">
                    <?php echo zen_image(DIR_WS_IMAGES . "Up-32.png", "UP"); ?>
                        </a>
    <?php }?>
                    </td>
                    <td align="center" style="width: 32px">
    <?php if($ix < $listing_products_label->RecordCount() - 1) {?>
                        <a href="javascript:void(0)" onclick="DOWN('<?php echo $listing_products_label->fields['products_label_id']; ?>')">
                   <?php echo zen_image(DIR_WS_IMAGES . "Down-32.png", "DOWN"); ?>
                        </a>
    <?php }?>
                    </td>            
                    <td align="center" class="dataTableContent">
                        <input type="text" class="ingredients" 
                            value="<?php echo $listing_products_label->fields['ingredients_description']; ?>" 
                            ddd="<?php echo $listing_products_label->fields['ingredients_ddd']; ?>" 
                            iid="<?php echo $listing_products_label->fields['ingredients_id']; ?>" />
                    </td>
                    <td align="center" class="dataTableContent">
                        <input type="text" class="value" onkeydown="enterUpdate(event, '<?php echo $listing_products_label->fields['products_label_id']; ?>')" value="<?php echo $listing_products_label->fields['products_label_qty_serving']; ?>" />
                    </td>
                    <td align="center" class="dataTableContent">
                        <span class="unit"><?php echo $listing_products_label->fields['ingredients_unit']; ?></span>
                    </td>
                    <td align="center" class="dataTableContent">
                        <select class="type">
                            <option value="1" <?php echo $listing_products_label->fields['products_label_position'] == "1" ? "selected" : ""; ?>>table</option>
                            <option value="2" <?php echo $listing_products_label->fields['products_label_position'] == "2" ? "selected" : ""; ?>>other_ingredients</option>
                            <option value="3" <?php echo $listing_products_label->fields['products_label_position'] == "3" ? "selected" : ""; ?>>informula</option>
                            <option value="4" <?php echo $listing_products_label->fields['products_label_position'] == "4" ? "selected" : ""; ?>>table_forward</option>
                            <option value="5" <?php echo $listing_products_label->fields['products_label_position'] == "5" ? "selected" : ""; ?>>table2</option>
                        </select>
                    </td>    
                    <td align="center" style="width: 45px">
                        <input type="button" value="Update" onclick="updateLabel('<?php echo $listing_products_label->fields['products_label_id']; ?>')" />
                        <input type="hidden" class="label_id" value="<?php echo $listing_products_label->fields['products_label_id'] ?>" />
                    </td>        
                    <td align="center" style="width: 45px">
                        <input type="button" value="Delete" onclick="deleteLabel('<?php echo $listing_products_label->fields['products_label_id']; ?>')" />            
                    </td>
                </tr>
<?php
        $ix += 1;
        $listing_products_label->MoveNext();
    }
}
?>
                <tr class="dataTableRow add">
                    <td>&nbsp;</td><td>&nbsp;</td>
                    <td align="center" class="dataTableContent">
                        <input type="text" class="ingredients" />    
                    </td>
                    <td align="center" class="dataTableContent">
                        <input type="text" class="value" value="" onkeyup="enterAdd(event)" />
                    </td>
                    <td align="center" class="dataTableContent">
                        <span class="unit"><?php echo $unit; ?></span>
                    </td>
                    <td align="center" class="dataTableContent">
                        <select class="type">
                            <option value="1">table</option>
                            <option value="2">other_ingredients</option>
                            <option value="3">informula</option>
                            <option value="4">table_forward</option>
                            <option value="5">table2</option>
                        </select>
                    </td>    
                    <td align="center" style="width: 45px">
                        <input type="button" id="btn_add_<?php echo $listing_products_label->fields['products_label_id'] ?>" value="Add" onclick="addLabel()" />
                    </td>        
                    <td align="center" style="width: 45px">&nbsp;</td>
                </tr>
            </table>
        </td>
        <td valign="top">
            <table cellspacing="0" cellpadding="0" border="1" style="margin-left:auto; margin-right:auto; margin-top: 20px; margin-bottom:30px; width: 100%">
                <tr><td colspan="2"><span>Tamanho da dose: <?php echo $products_serving_measurements; ?></span></td></tr>
                <tr><td style="width: 50%">Doses por produto: </td><td><?php echo $products_dosis; ?></td></tr>
                <tr><td colspan="2" valign="top">
                        <div id="divPreview"></div>
                    </td>
                </tr>                
            </table>
        </td>
    </tr>
</table>
    
<!-- body_eof //-->

<table id="tmpRowUpdate" style="display: none">
    <tr class="dataTableRow row_[ID]">
        <td align="center" style="width: 32px"><a href="javascript:void(0)" onclick="UP('[ID]')"><?php echo zen_image(DIR_WS_IMAGES . "Up-32.png", "UP"); ?></a></td>
        <td align="center" style="width: 32px"><a href="javascript:void(0)" onclick="DOWN('[ID]')"><?php echo zen_image(DIR_WS_IMAGES . "Down-32.png", "DOWN"); ?></a></td>
        <td align="center" class="dataTableContent">
            <input type="text" class="ingredients" />                
        </td>
        <td align="center" class="dataTableContent">
            <input type="text" class="value" value="" onkeydown="enterUpdate(event, '[ID]')" />
        </td>
        <td align="center" class="dataTableContent">
            <span class="unit"><?php echo $unit; ?></span>
        </td>
        <td align="center" class="dataTableContent">
            <select class="type">
                <option value="1">table</option>
                <option value="2">other_ingredients</option>
                <option value="3">informula</option>
                <option value="4">table_forward</option>
                <option value="5">table2</option>
            </select>
        </td>    
        <td align="center" style="width: 45px">
            <input type="button" value="Update" onclick="updateLabel('[ID]')" />
            <input type="hidden" class="label_id" value="[ID]" />
        </td>        
        <td align="center" style="width: 45px">
            <input type="button" value="Delete" onclick="deleteLabel('[ID]')" />            
        </td>
    </tr>
</table>
<!-- footer //-->
<div class="footer-area">
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
</div>
<!-- footer_eof //-->
<br />
</body>
<script type="text/javascript">    
    $(function(){        
        preview();
        $('input.ingredients').each(function(){            
            $(this).autocomplete({
                source: function(request, response) {
                    $.ajax({
                        type: "POST",
                        async: false,
                        dataType: "json",
                        url: 'ajax_products_label_insertion.php',
                        data: {term: request.term, lid: <?php echo $languages_english_id; ?>, cmd: "AUTO_SUGGESTION_INGREDIENTS"},
                        success: function(data) {
                            response($.map(data, function(item) {
                                return {
                                    label: item.desc,
                                    value: item.desc,      
                                    id: item.id,
                                    ddd: item.ddd,
                                    unit: item.unit
                                }
                            }));
                        }
                    });
                },
                minLength: 1,
                select: function(event, ui) {
                    var row = $(this).parent().parent();
                    if(ui.item)
                    {
                        $(this).val(ui.item.label);
                        $(this).attr('iid', ui.item.id);
                        $(this).attr('ddd', ui.item.ddd);
                        row.find('.unit').html(ui.item.unit);
                        setTimeout(function(){ row.find('.value').focus(); }, 100);
                    }                    
                }
            });
        });
    });
    
    function setAutoComplete(control)
    {
        $(control).autocomplete({
            source: function(request, response) {
                $.ajax({
                    type: "POST",
                    async: false,
                    dataType: "json",
                    url: 'ajax_products_label_insertion.php',
                    data: {term: request.term, lid: <?php echo $languages_english_id; ?>, cmd: "AUTO_SUGGESTION_INGREDIENTS"},
                    success: function(data) {
                        response($.map(data, function(item) {
                            return {
                                label: item.desc,
                                value: item.desc,      
                                id: item.id,
                                ddd: item.ddd,
                                unit: item.unit
                            }
                        }));
                    }
                });
            },
            minLength: 1,
            select: function(event, ui) {
                var row = $(this).parent().parent();
                if(ui.item)
                {
                    $(this).val(ui.item.label);
                    $(this).attr('iid', ui.item.id);
                    $(this).attr('ddd', ui.item.ddd);
                    row.find('.unit').html(ui.item.unit);
                    setTimeout(function(){ row.find('.value').focus(); }, 100);
                }                    
            }
        });
    }
    
    function preview()
    {
        var pid = $('#ddl_products_id').val();
        if(pid !== "")
        {
            $.ajax({
                type: "POST",
                async: false,
                url: 'ajax_products_label_insertion.php',
                data: {pid: pid,lid: <?php echo $languages_english_id; ?>, cmd: "REVIEW"},
                success: function (data) {                        
                    $("#divPreview").html(data);                        
                }
            });
        }
    }
    
    function addLabel()
    {
        var row = $('.add');
        var pid = $('#ddl_products_id').val();
        var serving_size = $('#products_serving_size').val();         
        if(pid === "")
        {
            alert("Please select a product to insert label");
            return;
        }
        if(serving_size !== "" && !isNaN(serving_size))
        {
            var ddd = row.find('.ingredients').attr('ddd');
            var ingredients_id = row.find('.ingredients').attr('iid');
            if(ingredients_id === "" || ingredients_id === "0" || isNaN(ingredients_id))
            {
                alert("Please enter ingredient.");
                setTimeout(function(){ row.find('.ingredients').focus(); }, 100);
                return false;
            }
            var position = row.find('.type').val();
            var value = row.find('.value').val();
            var qty_serving, qty_100, ddd_serving, ddr_100, position, sort;
            sort = $('#tblLabels > tbody').children().length - 1;
            if(ddd == "0")
            {
                qty_serving = value;
                qty_100 = parseFloat(value) * 100/parseFloat(serving_size);
                ddd_serving = "0";
                ddr_100 = "0";
            }
            else
            {
                if($('#rdServing').is(":checked"))
                {
                    qty_serving = value;
                    qty_100 = parseFloat(value) * 100/parseFloat(serving_size);
                    ddd_serving = parseFloat(value)/parseFloat(ddd);
                    ddr_100 = (parseFloat(value) * 100/parseFloat(serving_size))/parseFloat(ddd);
                }
                else
                {
                    qty_serving = parseFloat(value) * 100/parseFloat(serving_size);
                    qty_100 = value;
                    ddd_serving = (parseFloat(value) * 100/parseFloat(serving_size))/parseFloat(ddd);
                    ddr_100 = parseFloat(value)/parseFloat(ddd);
                }
            }
            $.ajax({
                    type: "POST",
                    async: false,
                    url: 'ajax_products_label_insertion.php',
                    data: {p_id: pid, i_id: ingredients_id, qty_serving: qty_serving
                        , qty_100: qty_100, ddd_serving: ddd_serving
                        , ddr_100: ddr_100, position: position, cmd: "ADD"},
                    success: function (data) {
                        if (!isNaN(data)) {				                
                            var html = $('#tmpRowUpdate > tbody').html();
                            html = html.replace('[ID]', data).replace('[ID]', data).replace('[ID]', data).replace('[ID]', data).replace('[ID]', data).replace('[ID]', data).replace('[ID]', data);                            
                            row.before(html);
                            $('.row_' + data).find('.value').val(row.find('.value').val());
                            $('.row_' + data).find('.type').val(row.find('.type').val());
                            $('.row_' + data).find('.ingredients').attr('ddd', row.find('.ingredients').attr('ddd'));
                            $('.row_' + data).find('.ingredients').attr('iid', row.find('.ingredients').attr('iid'));
                            $('.row_' + data).find('.ingredients').val(row.find('.ingredients').val());          
                            setAutoComplete($('.row_' + data).find('.ingredients'));
                            $('.row_' + data).find('.unit').html(row.find('.unit').html());
                            if(sort === 1)
                            {
                                $($('.row_' + data).children()[0]).html('');
                                $($('.row_' + data).children()[1]).html('');
                            }
                            else
                            {                             
                                $($('.row_' + data).children()[1]).html('');
                                var prev_row = $('.row_' + data).prev();
                                var prev_id = prev_row.find('.label_id').val();
                                $(prev_row.children()[1]).html('<a href="javascript:void(0)" onclick="DOWN(\'' + prev_id + '\')"><?php echo zen_image(DIR_WS_IMAGES . "Down-32.png", "DOWN"); ?></a>');
                            }
                            row.find('.value').val('');
                            row.find('.type').val('1');
                            row.find('.ingredients').val('');
                            row.find('.ingredients').attr('iid', '0');
                            row.find('.ingredients').attr('ddd', '0');
                            preview();
                        }
                        else
                            alert(data);
                    }
            });
        }
        else
        {
            alert("Please enter the product serving size");
        }
    }
    
    function updateLabel(id)
    {
        var row = $('.row_' + id);
        var pid = $('#ddl_products_id').val();
        var serving_size = $('#products_serving_size').val();         
        if(pid === "")
        {
            alert("Please select a product to insert label");
            return;
        }
        if(serving_size !== "" && !isNaN(serving_size) && serving_size !== "0")
        {
            var ddd = row.find('.ingredients').attr('ddd');
            var ingredients_id = row.find('.ingredients').attr('iid');
            if(ingredients_id === "" || ingredients_id === "0" || isNaN(ingredients_id) || row.find('.ingredients').val() === "")
            {
                alert("Please enter ingredient.");
                setTimeout(function(){ row.find('.ingredients').focus(); }, 100);
                return false;
            }
            var position = row.find('.type').val();
            var value = row.find('.value').val();
            var qty_serving, qty_100, ddd_serving, ddr_100, position; 
            if(ddd == "0")
            {
                qty_serving = value;
                qty_100 = parseInt(value) * 100/parseInt(serving_size);
                ddd_serving = "0";
                ddr_100 = "0";
            }
            else
            {
                if($('#rdServing').is(":checked"))
                {
                    qty_serving = value;
                    qty_100 = parseInt(value) * 100/parseInt(serving_size);
                    ddd_serving = parseFloat(value)/parseInt(ddd);
                    ddr_100 = (parseInt(value) * 100/parseInt(serving_size))/parseInt(ddd);
                }
                else
                {
                    qty_serving = parseInt(value) * 100/parseInt(serving_size);
                    qty_100 = value;
                    ddd_serving = (parseInt(value) * 100/parseInt(serving_size))/parseInt(ddd);
                    ddr_100 = parseFloat(value)/parseInt(ddd);
                }
            }
            $.ajax({
                    type: "POST",
                    async: false,
                    url: 'ajax_products_label_insertion.php',
                    data: {l_id: id, i_id: ingredients_id, qty_serving: qty_serving
                        , qty_100: qty_100, ddd_serving: ddd_serving
                        , ddr_100: ddr_100, position: position, cmd: "UPDATE"},
                    success: function (data) {
                        if (data === "SUCCESS") {				                
                            alert("Update product label successful.");
                            preview();
                        }
                        else
                            alert(data);
                    }
            });
        }
        else
        {
            alert("Please enter the product serving size");
        }
    }
    
    function deleteLabel(id)
    {
        var row = $('.row_' + id);     
        var prev_row = row.prev();
        var next_row = row.next();
        var index = row.index();
        $.ajax({
                    type: "POST",
                    async: false,
                    url: 'ajax_products_label_insertion.php',
                    data: {l_id: id, cmd: "DELETE"},
                    success: function (data) {
                        if (data === "SUCCESS") {				                
                            row.remove();
                            if(index === 1)
                            {
                                $(next_row.children()[0]).html('');
                            }
                            else if(index === $('#tblLabels > tbody').children().length - 1)
                            {                                
                                $(prev_row.children()[1]).html('');
                            }
                            preview();
                        }
                        else
                            alert(data);
                    }
            });
    }
    
    function UP(id)
    {
        var row = $('.row_' + id);
        var prev_row = row.prev();
        var prev_id = prev_row.find('.label_id').val();                
        $.ajax({
                    type: "POST",
                    async: false,
                    url: 'ajax_products_label_insertion.php',
                    data: {l_id: id, l_prev_id: prev_id, cmd: "UP"},
                    success: function (data) {
                        if (data === "SUCCESS") {	
                            var index = row.index();
                            var prev_index = prev_row.index();        
                            if(prev_index === 1)
                            {
                                $(row.children()[0]).html('');
                                $(prev_row.children()[0]).html('<a href="javascript:void(0)" onclick="UP(\'' + prev_id + '\')"><?php echo zen_image(DIR_WS_IMAGES . "Up-32.png", "UP"); ?></a>');
                                if($('#tblLabels > tbody').children().length === 4)//only have 2 labels
                                {
                                    $(prev_row.children()[1]).html('');
                                    $(row.children()[1]).html('<a href="javascript:void(0)" onclick="DOWN(\'' + id + '\')"><?php echo zen_image(DIR_WS_IMAGES . "Down-32.png", "DOWN"); ?></a>');
                                }
                            }
                            else if(index === $('#tblLabels > tbody').children().length - 2)
                            {
                                $(row.children()[1]).html('<a href="javascript:void(0)" onclick="DOWN(\'' + id + '\')"><?php echo zen_image(DIR_WS_IMAGES . "Down-32.png", "DOWN"); ?></a>');
                                $(prev_row.children()[1]).html('');
                            }
                            row.after(prev_row.clone());
                            setAutoComplete(row.next().find('.ingredients'));
                            prev_row.remove();
                            preview();
                        }
                        else
                            alert(data);
                    }
            });
    }
    
    function DOWN(id)
    {
        var row = $('.row_' + id);
        var next_row = row.next();
        var next_id = next_row.find('.label_id').val();            
        $.ajax({
                    type: "POST",
                    async: false,
                    url: 'ajax_products_label_insertion.php',
                    data: {l_id: id, l_next_id: next_id, cmd: "DOWN"},
                    success: function (data) {
                        if (data === "SUCCESS") {	
                            var index = row.index();
                            var next_index = next_row.index();        
                            if(index === 1)
                            {
                                $(row.children()[0]).html('<a href="javascript:void(0)" onclick="UP(\'' + id + '\')"><?php echo zen_image(DIR_WS_IMAGES . "Up-32.png", "UP"); ?></a>');
                                $(next_row.children()[0]).html('');
                                if($('#tblLabels > tbody').children().length === 4)//only have 2 labels
                                {
                                    $(row.children()[1]).html('');
                                    $(next_row.children()[1]).html('<a href="javascript:void(0)" onclick="DOWN(\'' + next_id + '\')"><?php echo zen_image(DIR_WS_IMAGES . "Down-32.png", "DOWN"); ?></a>');
                                }
                            }
                            else if(next_index === $('#tblLabels > tbody').children().length - 2)
                            {
                                $(row.children()[1]).html('');
                                $(next_row.children()[1]).html('<a href="javascript:void(0)" onclick="DOWN(\'' + next_id + '\')"><?php echo zen_image(DIR_WS_IMAGES . "Down-32.png", "DOWN"); ?></a>');
                            }

                            row.before(next_row.clone());
                            setAutoComplete(row.prev().find('.ingredients'));
                            next_row.remove();
                            preview();
                        }
                        else
                            alert(data);
                    }
            });
    }
    
    function enterUpdate(e, id)
    {
        var key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
        if(key == 13)
        {
            updateLabel(id);
        }
    }
    
    function enterAdd(e)
    {
        var key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
        if(key == 13)
        {
            addLabel();
        }
    }
    
    function selectUpdateIngredients(id)
    {
        var unit = $('.row_' + id).find('.ingredients :selected').attr('unit');
        $('.row_' + id).find('.unit').html(unit);
    }
    
    function confirmBefore()
    {
        var serving_size = $('#products_serving_size').val();
        if(serving_size == "" || isNaN(serving_size))
        {
            alert("Please input the Product Serving Size");
            return false;
        }
        if(confirm("Are you sure to want to update?\nAll products label info will update follow."))
        {
            $('#form_update_serving').submit();
        }
    }
    
    function selectLabelMeasurement(select)
    {
        var value = $(select).val();
        if(value.indexOf('s') < 0)
        {
            $('#products_serving_size').val(value.substring(0,1));
            $('#products_serving_size').attr('readonly', true);
            $('#products_serving_size_unit').val('');
            $('#products_serving_size_unit').attr('disabled', true);
        }
        else
        {            
            $('#products_serving_size').removeAttr('readonly');            
            $('#products_serving_size_unit').removeAttr('disabled');
        }        
    }
    
</script>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>